package com.hkyp.ss.course.apis.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.interfaces.DecodedJWT;

import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.Map;
import java.util.UUID;

public class JWTTokenUtil {

    //token密钥
    private static final String SECRET = "XX#$%dsafagsdlfj&MQ/*gfLMNQNQJQK sdfkjsdLJOoa34545fdf>?N<:{LWPW";

    // 默认五天过期
    public static final Long DEF_EXP = 1000*60*60*24*5L;

    // 邮箱激活链接  24小时有效
    public static final Long EMAIL_ACTIVE_EXP = 1000*60*60*24L;

    // 重置密码邮件链接有效期  24小时有效
    public static final Long RESETPWD_EMAIL_EXP = 1000*60*60*24L;


    /**
     * 获得token中的信息无需secret解密也能获得
     * @return token中包含的用户id
     */
    public static String getClaim(String token,String claim) {
        try {
            DecodedJWT jwt = JWT.decode(token);
            return jwt.getClaim(claim).asString();
        } catch (JWTDecodeException e) {
            return null;
        }
    }
    /**
     * 校验token是否正确
     * @param token 密钥
     * @return 是否正确
     *
     * 需满足两点才会验证成功：
     * 2.token没有过期
     * 3.能用相应的密钥和算法成功解开
     */
    public static boolean verifyWithNoId(String token) {
        try {
            Algorithm algorithm = Algorithm.HMAC256(SECRET);
            JWTVerifier verifier = JWT.require(algorithm)
                    .build();
            verifier.verify(token);
            return true;
        } catch (Exception exception) {
            return false;
        }
    }

    /**
     * 校验token是否正确
     * @param token 密钥
     * @return 是否正确
     *
     * 需满足两点才会验证成功：
     * 1.签发userid匹配
     * 2.token没有过期
     * 3.能用相应的密钥和算法成功解开
     */
    public static boolean verify(String token, String userId) {
        try {
            Algorithm algorithm = Algorithm.HMAC256(SECRET);
            JWTVerifier verifier = JWT.require(algorithm)
                    .withClaim("userId", userId)
                    .build();
            verifier.verify(token);
            return true;
        } catch (Exception exception) {
            return false;
        }
    }

    /**
     * 获得token中的信息无需secret解密也能获得
     * @return token中包含的用户id
     */
    public static String getUserId(String token) {
        try {
            DecodedJWT jwt = JWT.decode(token);
            return jwt.getClaim("userId").asString();
        } catch (JWTDecodeException e) {
            return null;
        }
    }

    /**
     *
     */
    public static String getInfo(String token,String claim) {
        try {
            DecodedJWT jwt = JWT.decode(token);
            return jwt.getClaim(claim).asString();
        } catch (JWTDecodeException e) {
            return null;
        }
    }
    /**
     * 获得token中的信息无需secret解密也能获得
     * @return token中包含的用户名
     */
    public static String getTokenIp(String token) {
        try {
            DecodedJWT jwt = JWT.decode(token);
            return jwt.getClaim("ip").asString();
        } catch (JWTDecodeException e) {
            return null;
        }
    }

    /**
     * 生成签名,指定时间后过期,一经生成不可修改，令牌在指定时间内一直有效
     * @param userId 用户Id
     * @param ip 登录ip
     * @return 加密的token
     */
    public static String sign(String userId,String ip,long expireTime) {
        try {
            Date date = new Date(System.currentTimeMillis()+expireTime);
            Algorithm algorithm = Algorithm.HMAC256(SECRET);
            // 附带username信息
            return JWT.create()
                    .withClaim("userId", userId)
                    .withClaim("ip",ip)

                    //.withClaim("userType",userType)
                    //.withClaim("userNumber",userNumber)
                    .withExpiresAt(date)
                    .sign(algorithm);
        } catch (UnsupportedEncodingException e) {
            return null;
        }
    }

    /***
     *
     * 常用信息key规定写法：
     *      userId   ip   email
     *
     */
    public static String signWithMap(Map<String,String> map, long expireTime) {
        try {
            Date date = new Date(System.currentTimeMillis()+expireTime);
            Algorithm algorithm = Algorithm.HMAC256(SECRET);

            // 附带username信息
            JWTCreator.Builder builder = JWT.create();

            for (String key: map.keySet()){
                builder.withClaim(key,map.get(key));
            }

            return   builder.withExpiresAt(date)
                    .sign(algorithm);

        } catch (UnsupportedEncodingException e) {
            return null;
        }
    }
//    public static void main(String[] args) throws InterruptedException {
//        System.out.println(UUID.randomUUID());
////        String sign = sign("1111","192.168.3.168",1125);
////        System.out.println(sign);
////        Thread.sleep(100L);
////        boolean verify = verify(sign, "1111");
////        System.out.println(verify);
////        System.out.println(getTokenIp(sign));
//
//
//    }

}
